package com.panda.expand.command;

import com.panda.command.Console;
import com.panda.expand.BodyParser;
import com.panda.expand.ParamElementHandler;
import com.panda.pojo.Context;
import com.panda.pojo.Element;

public class Fragment extends ParamElementHandler implements BodyParser {

    public static ParamElementHandler INSTANCE = new Fragment();

    private Fragment() {
        setPrefix("fragment");
        setRegex("\'[^']*\'");
    }

    @Override
    public String parseParam(Context context, Element element, String s) {

        s = s.substring(1, s.length() - 1);

        String[] strings = s.split("\\|");


        if (strings.length > 0) {
            String pre = strings[0];

            String[] split = pre.split(",");

            //倒叙遍历,向前追加
            for (int i = split.length - 1; i >= 0; i--) {

                String id = split[i];

                if (!id.equals("")) {

                    String fr = context.getFragments().get(id);

                    String bodyText = element.getBodyText();

                    //追加脚本
                    if (bodyText == null) {
                        bodyText = "";
                    }
                    element.setBodyText(fr + "\n" + bodyText);


                }
            }

        }


        if (strings.length > 1) {
            String pre = strings[1];

            String[] split = pre.split(",");

            //正序遍历,向后追加
            for (String id : split) {

                if (!id.equals("")) {

                    String fr = context.getFragments().get(id);

                    String bodyText = element.getBodyText();

                    //追加脚本
                    if (bodyText == null) {
                        bodyText = "";
                    }

                    element.setBodyText(bodyText + "\n" + fr);

                }
            }

        }


        if (strings.length > 2) {

            String other = "";

            for (int i = 2; i < strings.length; i++) {
                other += "|" + strings[i];
            }

            Console.warning("无法处理的参数: " + other);
        }


        //消费掉参数
        return null;
    }

}
